package com.flyme.common.reader;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.util.ClassUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 *
 */
@Slf4j
public class MybatisPagingReader<T> extends AbstractPagingReader<T> {

    private SqlSessionTemplate sqlSessionTemplate;

    private String queryId;

    private Map<String, Object> parameterValues;

    public MybatisPagingReader(SqlSessionFactory sqlSessionFactory, String queryId, Map<String, Object> parameterValues) {
        this.sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory);
        this.queryId = queryId;
        this.parameterValues = parameterValues;
    }

    public MybatisPagingReader(SqlSessionFactory sqlSessionFactory) {
        setName(ClassUtils.getShortName(MybatisPagingReader.class));
        initMybatisPagingReader(sqlSessionFactory);
    }

    private void initMybatisPagingReader(SqlSessionFactory sqlSessionFactory) {
        sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory);
    }

    public void setQueryId(String queryId) {
        this.queryId = queryId;
    }

    /**
     * The parameter values to be used for the query execution.
     *
     * @param parameterValues the values keyed by the parameter named used in
     *                        the query string.
     */
    public void setParameterValues(Map<String, Object> parameterValues) {
        this.parameterValues = parameterValues;
    }

    @Override
    protected void doReadPage() {
        Map<String, Object> parameters = new HashMap<String, Object>();
        if (parameterValues != null) {
            parameters.putAll(parameterValues);
        }
        parameters.put("_page", getPage());
        parameters.put("_pagesize", getPageSize());
        parameters.put("_skiprows", getPage() * getPageSize());
        if (results == null) {
            results = new CopyOnWriteArrayList<T>();
        } else {
            results.clear();
        }
        results.addAll(execute(parameters));
    }

    @SuppressWarnings("unchecked")
    private List<T> execute(Map<String, Object> parameters) {
        return sqlSessionTemplate.selectList(queryId, parameters);
    }
}
